using System.Collections.Generic;
using Entitas;
using UnityEngine;

public sealed class AddViewSystem : ReactiveSystem, IInitializeSystem
{

    public AddViewSystem(Contexts contexts) : base(contexts.core) {
        _context = contexts.core;
    }

    protected override Collector GetTrigger(Context context) {
        return context.CreateCollector(CoreMatcher.Asset);
    }

    protected override bool Filter(Entity entity) {
        return true;
    }

    readonly Context _context;
    Transform _container;

    

    public void Initialize() {
        _container = new GameObject(_context.contextInfo.name + " Views").transform;
    }

    protected override void Execute(List<Entity> entities) {
        foreach(var e in entities) {
            var gameObject = Assets.Instantiate<GameObject>(e.asset.name);
            var parent = _container;
            if (e.HasComponent(CoreComponentIds.Parent))
            {
                parent = e.parent.transform;
            }
            gameObject.transform.SetParent(parent, false);
            gameObject.Link(e, _context);
            e.AddView(gameObject.GetComponent<IViewController>());
        }
    }
}
